import type { RouteRecordRaw } from 'vue-router';
import { usePermissionStore } from '@/store/modules/permission';
import { useTabs } from './useTabs';
import { router, resetRouter } from '@/router';
import { useMultipleTabStore } from '@/store/modules/multipleTab';
import { isArray } from '@/utils/is';
import { useUserStore } from '@/store/modules/user';
import { intersection } from 'lodash-es';

// User permissions related operations
export function usePermission() {
	const permissionStore = usePermissionStore();
	const userStore = useUserStore();
	const { closeAll } = useTabs(router);

	/**
	 * Reset and regain authority resource information
	 * @param id
	 */
	async function resume() {
		const tabStore = useMultipleTabStore();
		tabStore.clearCacheTabs();
		resetRouter();
		const routes = await permissionStore.buildRoutesAction();
		routes.forEach(route => {
			router.addRoute(route as unknown as RouteRecordRaw);
		});
		closeAll();
	}

	/**
	 * 根据角色code判断是否拥有权限
	 * TOCHANGE: 根据业务接口格式修改
	 */
	function hasPermission(value?: string | string[], def = true): boolean {
		if (!value) {
			return def;
		}

		const roleCodeList = userStore.getRoleInfo.map(({ roleCode }) => roleCode) || [];
		if (isArray(value)) {
			return (intersection(value, roleCodeList) as string[]).length > 0;
		}
		return roleCodeList.includes(value as string);
	}

	/**
	 * refresh menu data
	 */
	async function refreshMenu() {
		resume();
	}

	return { hasPermission, refreshMenu };
}
